package com.jbm.jbmsupplier.activity.address.audiovideo;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.cjt2325.cameralibrary.JCameraView;
import com.cjt2325.cameralibrary.lisenter.JCameraLisenter;
import com.jbm.jbmsupplier.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by 家帮忙 on 2017/9/27.
 */

public class CamerActivity extends Activity {
    @InjectView(R.id.jcameraview)
    JCameraView jcameraview;
    private final int GET_PERMISSION_REQUEST = 100; //权限申请自定义码
    private boolean granted = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layoutcamer);
        ButterKnife.inject(this);
        //设置视频保存路径
        jcameraview.setSaveVideoPath(Environment.getExternalStorageDirectory().getPath() + File.separator + "JBMCamera");

        //JCameraView监听
        jcameraview.setJCameraLisenter(new JCameraLisenter() {
            @Override
            public void captureSuccess(Bitmap bitmap) {
                //获取图片bitmap
            }

            @Override
            public void recordSuccess(String url, Bitmap firstFrame) {
                String urlpic = saveBitmap(firstFrame);
//                Log.i("JBM", "v"+url.substring(url.indexOf("v")+1,url.length()));
                Intent intent=new Intent();
                intent.putExtra("file",url);
                intent.putExtra("name","v"+url.substring(url.indexOf("v")+1,url.length()));
                intent.putExtra("pic",urlpic);
                setResult(RESULT_OK, intent);
                finish();
            }
            @Override
            public void quit() {
                //退出按钮
                finish();
            }
        });
        //6.0动态权限获取
        getPermissions();
    }

    /**
     * 保存方法
     */
    public String saveBitmap(Bitmap bitmap) {
        String uri = "JBM_Pic" + System.currentTimeMillis() + ".png";
        File f = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "JBM",uri);
        if (!f.exists()) {
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            BitmapFactory.Options options = new  BitmapFactory.Options();
            options.inSampleSize = 2 ; //图片宽高都为原来的二分之一，即图片为原来的四分之一
            Bitmap bs = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + File.separator + "JBM"+uri, options);
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 70, out);
            out.flush();
            out.close();
            Log.i("JBM", "已经保存");
            return Environment.getExternalStorageDirectory().getPath() + File.separator + "JBM" + File.separator + uri;
        } catch (FileNotFoundException e) {
            Log.i("JBM", "已经保存"+e);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }





    @Override
    protected void onStart() {
        super.onStart();
        //全屏显示
        if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        } else {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(option);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (granted) {
            jcameraview.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        jcameraview.onPause();
    }

    /**
     * 获取权限
     */
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED&&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ) {
                //具有权限
                granted = true;
            } else {
                //不具有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(CamerActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, GET_PERMISSION_REQUEST);
                granted = false;
            }
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == GET_PERMISSION_REQUEST) {
            int size = 0;
            if (grantResults.length >= 1) {
                int writeResult = grantResults[0];
                //读写内存权限
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;//读写内存权限
                if (!writeGranted) {
                    size++;
                }
                //录音权限
                int recordPermissionResult = grantResults[1];
                boolean recordPermissionGranted = recordPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!recordPermissionGranted) {
                    size++;
                }
                //相机权限
                int cameraPermissionResult = grantResults[2];
                boolean cameraPermissionGranted = cameraPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!cameraPermissionGranted) {
                    size++;
                }
                //相机权限
                int cameraPermissionResults = grantResults[3];
                boolean cameraPermissionGranteds = cameraPermissionResults == PackageManager.PERMISSION_GRANTED;
                if (!cameraPermissionGranteds) {
                    size++;
                }



                if (size == 0) {
                    granted = true;
                    jcameraview.onResume();
                }else{
                    Toast.makeText(this, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }







}
